package main

import "fmt"

// 给你一个m行n列的矩阵matrix，请按照顺时针螺旋顺序，返回矩阵中的所有元素。
// 输入：matrix =[[1,2,3],
//				 [4,5,6],
//				 [7,8,9]]
// 输出：[1,2,3,6,9,8,7,4,5]

func main() {
	var (
		matrix = [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
	)
	res := spiralOrder(matrix)
	fmt.Println("输出", res)
}

func spiralOrder(matrix [][]int) []int {
	var (
		result = make([]int, 0)
	)

	if len(matrix) == 0 || len(matrix[0]) == 0 {
		return result
	}

	top, bottom, left, right := 0, len(matrix)-1, 0, len(matrix[0])-1

	for top <= bottom && left <= right {
		// 上
		for i := left; i <= right; i++ {
			result = append(result, matrix[top][i])
		}
		top++

		// 右
		for i := top; i <= bottom; i++ {
			result = append(result, matrix[i][right])
		}
		right--

		// 下
		for i := right; i >= left; i-- {
			result = append(result, matrix[bottom][i])
		}
		bottom--

		// 左
		for i := bottom; i >= top; i-- {
			result = append(result, matrix[i][left])
		}
		left++
	}
	return result
}
